<template>
	<view id="goodsListContainer">
		<view class="goodsListBox">
			<view @click="swichToGoodsDetail(item)" v-for="(item,index) in goodsList" :key="item.goods_id">
				<goods :goods="item"></goods>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 商品列表请求参数
				goodsListData:{
					query:"",
					cid:"",
					pagenum:1,
					pagesize:20
				},
				goodsList:[],
				total:'',
				defaultImg:'https://img3.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png',
				// 节流标记
				isLoading:false
			};
		},
		onLoad(options){
			// 将页面跳转时携带的参数存储
			this.goodsListData.query = options.query || ''
			this.goodsListData.cid = options.cid || ''
			this.getGoodsListData()
		},
		methods:{
			async getGoodsListData(cb){
				// 修改节流标记，触发节流
				this.isLoading = true
				const {data:res} = await uni.$http.get('/api/public/v1/goods/search',this.goodsListData)
				// 按需调用关闭下拉事件
				cb && cb()
				if(res.meta.status === 200){
					this.goodsList = [...this.goodsList,...res.message.goods]
					this.total = res.message.total
				}else{
					return uni.$showMsg()
				}
				// 修改节流标记
				this.isLoading = false
			},
			// 跳转至商品详情界面
			swichToGoodsDetail(item){
				uni.navigateTo({
					url:"/subpkg/goods_detail/goods_detail?goods_id="+item.goods_id
				})
			},
			// 下拉触底事件
			onReachBottom(){
				if(this.isLoading) return
				// 当页码数*页数大于总条数的时候数据加载完毕，此时不在发起请求
				if(this.goodsListData.pagenum*this.goodsListData.pagesize>=this.total){
					return uni.showToast({
								title:"加载完毕"
							})		
				}
				this.goodsListData.pagenum++
				this.getGoodsListData()
			},
			// 上拉刷新事件
			onPullDownRefresh(){
				this.goodsListData.pagenum = 1
				this.total = 0
				this.isLoading = false
				this.goodsList = []
				// this.getGoodsListData为异步方法，这样写可以确保关闭下拉事件在this.getGoodsListData执行完毕之后执行
				this.getGoodsListData(() =>
					// 关闭下拉事件
					uni.stopPullDownRefresh()
				)	
			}
		}
	}
</script>

<style lang="scss">

</style>
